package com.betterjr.common.web;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.betterjr.common.utils.Collections3;

public abstract class AbstarctRemoteApiInvoke {

    private static final Logger logger = LoggerFactory.getLogger(AbstarctRemoteApiInvoke.class);

    public abstract String saveOrFindInvoke(AjaxRemoteApiParam param);

    public abstract boolean supportInvoke(String apiCode);

    public abstract boolean checkParam(Map<String, Object> anParamMap);

    public String findProperties(Map<String, Object> anParamMap, String key) {

        if (!Collections3.isEmpty(anParamMap) && anParamMap.containsKey(key)) {
            return anParamMap.get(key).toString();
        }

        return "";
    }

    public String findProperties(Map<String, Object> anParamMap, String key, String defaultValue) {

        String string = findProperties(anParamMap, key);

        if (StringUtils.isBlank(string)) {
            string = defaultValue;
        }

        return string;
    }

    public boolean checkPre(AjaxRemoteApiParam param) {
        return true;
    }

    public <T> T findProperties(Map map, String key, Class<T> requiredType) {

        return findProperties(map, key, requiredType, null);

    }

    @SuppressWarnings("unchecked")
    public <T> T findProperties(Map map, String key, Class<T> requiredType, Object defaultObj) {

        if (map != null && map.containsKey(key)) {

            Object object = map.get(key);

            if (requiredType != null && object != null && StringUtils.isNoneBlank(object.toString())) {

                if (requiredType.isInstance(object)) return (T) object;

                if (requiredType.isAssignableFrom(Integer.class) || requiredType.isAssignableFrom(int.class)) {
                    return (T) Integer.valueOf(object.toString());
                }

                if (requiredType.isAssignableFrom(String.class)) {
                    return (T) object.toString();
                }
                if (requiredType.isAssignableFrom(Long.class) || requiredType.isAssignableFrom(long.class)) {
                    return (T) Long.valueOf(object.toString());
                }
                if (requiredType.isAssignableFrom(boolean.class) || requiredType.isAssignableFrom(Boolean.class)) {
                    return (T) Boolean.valueOf(object.toString());
                }

                if (requiredType.isAssignableFrom(String[].class)) {
                    return (T) new String[] { object.toString() };
                }

            }

        }

        if (requiredType.isInstance(defaultObj)) return (T) defaultObj;

        return null;

    }

}
